home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2195 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.3 KB

  1. Path: ix.netcom.com!netnews
  2. From: a1s@ix.netcom.com (Andrew Snyder)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: quick decision: is n a power of 2?
  5. Date: Fri, 19 Jan 1996 22:33:52 GMT
  6. Organization: Netcom
  7. Message-ID: <4dorr8$i58@cloner3.netcom.com>
  8. References: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca>
  9. NNTP-Posting-Host: ix-har6-12.ix.netcom.com
  10. X-NETCOM-Date: Fri Jan 19 11:36:08 AM PST 1996
  11. X-Newsreader: Forte Free Agent 1.0.82
  12.  
  13. Bill Simpson <wsimpson@uwinnipeg.ca> wrote:
  14.  
  15. >Is there a fast way to decide whether a number n is a power of 2?
  16.  
  17. >In my problem
  18. >if ((high-low+1) is a power of 2)
  19. >    {
  20. >    do one thing
  21. >    }
  22. >else
  23. >    {
  24. >    do another
  25. >    }
  26. >e.g. low=0, high=7: 7-0+1 is a power of 2.
  27.  
  28. >The only thing I have thought of is that if n is power of 2
  29. >log(n)/log(2) is an integer
  30. >BUT this is going to be a SLOW computation.  Needs to be fast.
  31.  
  32. >Since I am dealing with unsigned long ints, I guess I can just store all
  33. >31 powers of 2 in a table and compare to n.  Though I don't know a fast
  34. >algorithm to compare a number to 31 numbers in an array.
  35.  
  36. >Perhaps there is a tricky nonportable way to see if I have power-of-2 by 
  37. >looking at bits?  (That is fine for this application)
  38.  
  39. >Thanks very much for any help.
  40.  
  41. >Bill Simpson
  42.  
  43. no tricks
  44.  
  45. #define ISPOW2(x) (((x) & 1) ^ 1)
  46.  
  47.  
  48. Andrew Snyder
  49. a1s@ix.netcom.com
  50. char disclaimer[] = {'\0'}; /* I'm on cash net */
  51.  
  52.